﻿Imports System.Data.Entity
Imports QLQA.Migrations

Public Class frmMain


    Public DanhMucs As List(Of DanhMuc)
    Public Bans As List(Of Ban)
    Public SanPhams As List(Of SanPham)
    Public Sub New()
        Dim frm = New frmDangNhap
        frm.ShowDialog()
        InitializeComponent()
    End Sub
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
     
        ' Database.SetInitializer(New MigrateDatabaseToLatestVersion(Of QlqaContext, Configuration)())
        ' Chạy lệnh 'Enable-Migrations'
        ' Chạy lệnh 'Add-Migration TenMigration'
        ' Chạy lệnh 'Update-Database' để cập nhật database 

        If IsNothing(MySession.ThanhVien) Then

            InputMoBan(True)
            tsbDangNhap.Enabled = True
            btnMoBan.Enabled = False
            tsbMoBan.Enabled = False
           
            HệThốngToolStripMenuItem.Enabled = False
            DanhMụcToolStripMenuItem2.Enabled = False
            DanhMụcToolStripMenuItem1.Enabled = False

            Exit Sub
        End If

        InputMoBan(True)
        btnMoBan.Enabled = False
        tsbMoBan.Enabled = False
        HệThốngToolStripMenuItem.Enabled = True
        DanhMụcToolStripMenuItem2.Enabled = True
        DanhMụcToolStripMenuItem1.Enabled = True

        tsbDangNhap.Enabled = False
        txtLoiChao.Text = String.Format("Chào : {0}", MySession.ThanhVien.TenThat)

        LoadInput()


    End Sub
    Private Sub tsbDangNhap_Click(sender As System.Object, e As System.EventArgs) Handles tsbDangNhap.Click
        Dim frm = New frmDangNhap
        frm.ShowDialog()

        Form1_Load(sender, e)

    End Sub
    Public Sub LoadInput()
        Using db = New QlqaContext
            LoadDanhMuc(db)
            LoadBan(db)
            SanPhams = db.SanPhams.Include("DanhMuc").ToList()
            LoadSpanPhams(SanPhams)
        End Using

    End Sub
    Sub LoadDanhMuc(db As QlqaContext)
        DanhMucs = db.DanhMucs.ToList()
        DanhMucs.Insert(0, New DanhMuc() With {.Id = 0, .Ten = "Tất cả"})
        cboDanhMuc.DataSource = DanhMucs.Select(Function(x) x.Ten).ToArray()
    End Sub
    Sub LoadSpanPhams(sps As List(Of SanPham))
        If IsNothing(sps) Then
            Exit Sub
        End If
        lvMon.Items.Clear()
        For Each o In sps
            Dim i = New ListViewItem()
            i.Tag = o
            i.SubItems.Add(o.Ten)
            i.SubItems.Add(o.Gia.Format("."))
            lvMon.Items.Add(i)
        Next

        CapNhatSoThuTuMon()
    End Sub
    Private Sub CapNhatSoThuTuMon()
        For i As Integer = 1 To lvMon.Items.Count
            lvMon.Items(i - 1).Text = i.ToString()
        Next
    End Sub
    Private Sub DanhMụcToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DanhMụcToolStripMenuItem3.Click
        Dim frm = New frmDanhMuc
        AddHandler frm.OnUpdate, AddressOf OnUpdateDanhMuc
        frm.ShowDialog()
    End Sub


    Private Sub OnUpdateDanhMuc(sender As System.Object, e As System.EventArgs)
        Using db = New QlqaContext
            LoadDanhMuc(db)
        End Using
    End Sub
    Private Sub SảnPhẩmToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SảnPhẩmToolStripMenuItem1.Click
        Dim frm = New frmSanPham()
        AddHandler frm.OnUpdate, AddressOf OnUpdateSanPham
        frm.ShowDialog()
    End Sub

    Private Sub OnUpdateSanPham(sender As System.Object, e As System.EventArgs)
        Using db = New QlqaContext
            SanPhams = db.SanPhams.Include("DanhMuc").ToList()
            LoadSpanPhams(SanPhams)

        End Using
    End Sub
    Private Sub BànToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles BànToolStripMenuItem1.Click
        Dim frm = New frmBan()
        AddHandler frm.OnUpdate, AddressOf OnUpdateBan
        frm.ShowDialog()
    End Sub



    Private Sub OnUpdateBan(sender As System.Object, e As System.EventArgs)
        Using db = New QlqaContext
            LoadBan(db)

        End Using
    End Sub

    Sub LoadBan(db As QlqaContext)

        lvBan.Items.Clear()
        Bans = db.Bans.ToList()
        For Each o In Bans
            Dim i = New ListViewItem(o.Ten, Convert.ToInt32(IIf(o.DaSuDung, 1, 0)))
            i.Tag = o
            lvBan.Items.Add(i)
        Next


    End Sub

    Private Sub ThànhViênToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ThànhViênToolStripMenuItem.Click
        Dim frm = New frmThanhVien()
        frm.ShowDialog()
    End Sub

  
    Private Sub cboDanhMuc_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboDanhMuc.SelectedValueChanged
        Dim strText As String = cboDanhMuc.Text
        If Not String.IsNullOrEmpty(strText) Then
            LoadSpanPhams(SanPhams.Where(strText <> "Tất cả", Function(x) x.DanhMuc.Ten = strText).ToList())

        End If

    End Sub

    Private Sub btnTim_Click(sender As System.Object, e As System.EventArgs) Handles btnTim.Click, txtTuKhoa.TextChanged
        Dim strText As String = txtTuKhoa.Text.BoDau().ToLower()
        Dim strDanhMuc As String = cboDanhMuc.Text

        LoadSpanPhams(SanPhams _
                      .Where(strDanhMuc <> "Tất cả", Function(x) x.DanhMuc.Ten = strDanhMuc) _
                      .Where(Not String.IsNullOrEmpty(strText), Function(x) x.Ten.BoDau().ToLower().Contains(strText)) _
                      .ToList())


    End Sub

    Private Sub lvMon_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lvMon.SelectedIndexChanged
        If lvMon.SelectedItems.Count = 0 Then Return

        Dim obj As SanPham = lvMon.SelectedItems(0).Tag
        If Not IsNothing(obj) Then
            lblMon.Text = String.Format("Món: {0}", obj.Ten)
            lblMon.Tag = obj
        End If

    End Sub

    Private Sub lvBan_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lvBan.SelectedIndexChanged
        If sender.SelectedItems.Count = 0 Then Return
        Dim obj As Ban = sender.SelectedItems(0).Tag
        If Not IsNothing(obj) Then
            If Not obj.DaSuDung Then
                'Nếu chưa sử dụng
                lblBan.Text = String.Format("{0}: Chưa sử dụng ", obj.Ten)
                SetThanhTien(0)
                'Xử lý cac button
                InputMoBan(True)
                lvHoaDon.Items.Clear()

            Else
                'Nếu đã mở bàn rồi 
                'Liệt kê các món đã gọi

                Using db = New QlqaContext
                    Dim ban = db.Bans.FirstOrDefault(Function(x) x.Id = obj.Id)
                    'Dim hd = db.DonHangs.FirstOrDefault(Function(x) x.Id = ban.IdDonHang)
                    Dim hd = db.DonHangs.ToList().Select(Function(x) New DonHang() With {.Id = x.Id, .Ban = x.Ban, _
                                                     .DaThanhToan = x.DaThanhToan, _
                                                     .ThanhTien = x.ThanhTien, _
                                                     .ChiTietDonHangs = db.ChiTietDonHangs.Where(Function(o) o.DonHang.Id = x.Id).ToList().Select(Function(c) New ChiTietDonHang() With {.Id = c.Id, .DonGia = c.DonGia, .DonHang = c.DonHang, .SanPham = db.SanPhams.ToList().FirstOrDefault(Function(s) s.Id = c.SanPham.Id), .SoLuong = c.SoLuong}).ToList()}).ToList() _
                                             .FirstOrDefault(Function(x) x.Id = ban.IdDonHang)




                    InputMoBan(False)

                    'Load HoaDon 

                    LoadLvHoaDon(hd)

                    lblBan.Text = String.Format("Đang sử dụng: {0}", obj.Ten)
                    ' Dim lo = lblThanhTien.Location
                    SetThanhTien(hd.ThanhTien)

                    ' lblThanhTien.Location = New System.Drawing.Point(219, 94)
                End Using
            End If

            lblBan.Tag = obj
        End If
    End Sub

  

    Private Sub btnMoBan_Click(sender As System.Object, e As System.EventArgs) Handles btnMoBan.Click, tsbMoBan.Click
        Dim objB As Ban = lblBan.Tag

        If objB IsNot Nothing AndAlso Not objB.DaSuDung Then
            Using db = New QlqaContext
                'Thêm vào DonHang
                Dim ban = db.Bans.FirstOrDefault(Function(x) x.Id = objB.Id)
                Dim dh = New DonHang
                dh.Ban = ban

                db.DonHangs.Add(dh)
                db.SaveChanges()
                ban.IdDonHang = dh.Id
                ban.DaSuDung = True

                db.SaveChanges()
                lblBan.Tag = ban
                SetIconBan(ban, 1)
            End Using
            ' Mở Input
            InputMoBan(False)
            lblBan.Text = String.Format("Đang sử dụng: {0} ", objB.Ten)
            lvHoaDon.Items.Clear()

        End If
    End Sub

    Sub InputMoBan(val As Boolean)
        btnMoBan.Enabled = val
        tsbMoBan.Enabled = val
        tsbGopBan.Enabled = (val <> True)
        tsbThanhToan.Enabled = (val <> True)
        tsbHuyBan.Enabled = (val <> True)

        btnThanhToan.Enabled = (val <> True)
        btnGopBan.Enabled = (val <> True)
        btnBoMon.Enabled = (val <> True)
        btnThemMon.Enabled = (val <> True)
        btnThanhToan.Enabled = (val <> True)

    End Sub

    Private Sub tsbHuyBan_Click(sender As System.Object, e As System.EventArgs) Handles tsbHuyBan.Click
        Dim objB As Ban = lblBan.Tag

        If objB IsNot Nothing AndAlso objB.DaSuDung Then

            Dim dr As DialogResult = MessageBox.Show("Bạn có thực sự muốn hủy?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            ' Nếu người dùng lựa chọn đồng ý
            If dr = Windows.Forms.DialogResult.Yes Then
                Using db = New QlqaContext
                    Dim ban = db.Bans.FirstOrDefault(Function(x) x.Id = objB.Id)
                    'Xóa DonHang


                    For Each chiTietDonHang As ChiTietDonHang In db.ChiTietDonHangs.Where(Function(x) x.DonHang.Id = ban.IdDonHang)
                        db.ChiTietDonHangs.Remove(chiTietDonHang)
                    Next

                    db.SaveChanges()

                    db.DonHangs.Remove(db.DonHangs.FirstOrDefault(Function(x) x.Id = ban.IdDonHang))
                    db.SaveChanges()

                    ban.IdDonHang = 0
                    ban.DaSuDung = False

                    db.SaveChanges()
                    SetIconBan(ban, 0)
                    lblBan.Text = String.Format("{0}: Chưa sử dụng ", ban.Ten)
                    SetThanhTien(0)
                    lblBan.Tag = ban
                    lvHoaDon.Items.Clear()

                    InputMoBan(True)
                End Using
            End If

        End If
    End Sub
    Sub SetThanhTien(tien As Integer)
        lblThanhTien.Text = String.Format("Thành tiền: {0} VNĐ", tien.Format())
    End Sub
    Sub SetIconBan(b As Ban, val As Integer)
        For Each item As ListViewItem In lvBan.Items
            Dim objB As Ban = item.Tag
            If objB IsNot Nothing Then
                If objB.Id = b.Id Then
                    item.ImageIndex = val
                    item.Tag = b
                End If
            End If
        Next
    End Sub

    Private Sub btnThemMon_Click(sender As System.Object, e As System.EventArgs) Handles btnThemMon.Click
        Dim objB As Ban = lblBan.Tag

        If objB IsNot Nothing AndAlso objB.DaSuDung Then

            Dim objM As SanPham = lblMon.Tag
            If objM Is Nothing Then
                MessageBox.Show("Chọn món trước", "Thông báo")
                Exit Sub
            End If
            'Thêm món vào ChiChiDonHang
            Using db = New QlqaContext
                'Get DonHang
                Dim dh = db.DonHangs.ToList().Select(Function(x) New DonHang() With {.Id = x.Id, .Ban = x.Ban, _
                                                        .DaThanhToan = x.DaThanhToan, _
                                                        .ThanhTien = x.ThanhTien, _
                                                        .ChiTietDonHangs = db.ChiTietDonHangs.Where(Function(o) o.DonHang.Id = x.Id).ToList().Select(Function(c) New ChiTietDonHang() With {.Id = c.Id, .DonGia = c.DonGia, .DonHang = c.DonHang, .SanPham = db.SanPhams.ToList().FirstOrDefault(Function(s) s.Id = c.SanPham.Id), .SoLuong = c.SoLuong}).ToList()}).ToList() _
                                                .FirstOrDefault(Function(x) x.Id = objB.IdDonHang)
            


                'Tim xem món này có trong thực đơn chưa
                'Có thi tăng số lượng không thi thêm mới
                Dim dbSanPham = db.SanPhams.FirstOrDefault(Function(x) x.Id = objM.Id)


                Dim ctS As ChiTietDonHang = dh.ChiTietDonHangs.ToList().FirstOrDefault(Function(x) x.SanPham.Id = dbSanPham.Id And x.DonHang.Id = dh.Id)
                Dim dhS = db.DonHangs.FirstOrDefault(Function(x) x.Id = objB.IdDonHang)
                If ctS Is Nothing Then


                    ctS = New ChiTietDonHang()
                    ctS.SanPham = dbSanPham
                    ctS.DonHang = dhS
                    ctS.SoLuong = nudSoLuong.Value
                    ctS.DonGia = objM.Gia
                    dhS.ChiTietDonHangs.Add(ctS)

                Else
                    ctS = dhS.ChiTietDonHangs.FirstOrDefault(Function(x) x.SanPham.Id = dbSanPham.Id And x.DonHang.Id = dh.Id)
                    'Cập nhật số lượng
                    ctS.SoLuong += nudSoLuong.Value
                End If

                'Cập nhật thành tiền
                dhS.ThanhTien = dhS.ChiTietDonHangs.Sum(Function(x) x.DonGia * x.SoLuong)
                SetThanhTien(dhS.ThanhTien)
                db.SaveChanges()

                LoadLvHoaDon(dhS)

            End Using


        End If
    End Sub

    Sub LoadLvHoaDon(ls As DonHang)

        If IsNothing(ls) Then
            Exit Sub
        End If
        lvHoaDon.Items.Clear()
        For Each o In ls.ChiTietDonHangs
            Dim i = New ListViewItem()
            i.Tag = o
            i.SubItems.Add(o.SanPham.Ten)
            i.SubItems.Add(o.SoLuong.Format())
            i.SubItems.Add(o.DonGia.Format())
            i.SubItems.Add((o.DonGia * o.SoLuong).Format())
            lvHoaDon.Items.Add(i)
        Next

        CapNhatSoThuTuHoaDon()
    End Sub
    Private Sub CapNhatSoThuTuHoaDon()
        For i As Integer = 1 To lvHoaDon.Items.Count
            lvHoaDon.Items(i - 1).Text = i.ToString()
        Next
    End Sub

    Private Sub btnBoMon_Click(sender As System.Object, e As System.EventArgs) Handles btnBoMon.Click
        If lvHoaDon.SelectedItems.Count = 0 Then
            Exit Sub
        End If

        Dim objB As Ban = lblBan.Tag

        If objB IsNot Nothing AndAlso objB.DaSuDung Then
            Using db = New QlqaContext
                For Each listViewItem As ListViewItem In lvHoaDon.SelectedItems

                    Dim ctD As ChiTietDonHang = listViewItem.Tag

                    'Get DonHang
                    Dim dh = db.DonHangs.ToList().Select(Function(x) New DonHang() With {.Id = x.Id, .Ban = x.Ban, _
                                                            .DaThanhToan = x.DaThanhToan, _
                                                            .ThanhTien = x.ThanhTien, _
                                                            .ChiTietDonHangs = db.ChiTietDonHangs.Where(Function(o) o.DonHang.Id = x.Id).ToList().Select(Function(c) New ChiTietDonHang() With {.Id = c.Id, .DonGia = c.DonGia, .DonHang = c.DonHang, .SanPham = db.SanPhams.ToList().FirstOrDefault(Function(s) s.Id = c.SanPham.Id), .SoLuong = c.SoLuong}).ToList()}).ToList() _
                                                    .FirstOrDefault(Function(x) x.Id = objB.IdDonHang)




                    Dim ctS As ChiTietDonHang = dh.ChiTietDonHangs.FirstOrDefault(Function(x) x.SanPham.Id = ctD.SanPham.Id And x.DonHang.Id = dh.Id)
                    Dim dhS = db.DonHangs.FirstOrDefault(Function(x) x.Id = objB.IdDonHang)
                    If ctS IsNot Nothing Then


                        ctS = dhS.ChiTietDonHangs.FirstOrDefault(Function(x) x.SanPham.Id = ctD.SanPham.Id And x.DonHang.Id = dh.Id)
                        'Cập nhật số lượng
                        ctS.SoLuong -= nudSoLuong.Value
                        listViewItem.SubItems(2).Text = ctS.SoLuong.Format()
                        listViewItem.SubItems(4).Text = (ctS.SoLuong * ctS.DonGia).Format()
                        If (ctS.SoLuong < 1) Then

                            db.ChiTietDonHangs.Remove(ctS)
                            db.SaveChanges()
                            listViewItem.Remove()
                            CapNhatSoThuTuHoaDon()
                        End If

                    End If

                    'Cập nhật thành tiền
                    dhS.ThanhTien = dhS.ChiTietDonHangs.Sum(Function(x) x.DonGia * x.SoLuong)

                    SetThanhTien(dhS.ThanhTien)
                    db.SaveChanges()
                Next
            End Using
        End If

    End Sub

    Private Sub btnThanhToan_Click(sender As System.Object, e As System.EventArgs) Handles btnThanhToan.Click, tsbThanhToan.Click

        Dim objB As Ban = lblBan.Tag

        If objB IsNot Nothing AndAlso objB.DaSuDung Then
            Dim dh As DonHang
            Using db = New QlqaContext
                dh = db.DonHangs.ToList().Select(Function(x) New DonHang() With {.Id = x.Id, .Ban = x.Ban, _
                                                         .DaThanhToan = x.DaThanhToan, _
                                                         .ThanhTien = x.ThanhTien, _
                                                         .ChiTietDonHangs = db.ChiTietDonHangs.Where(Function(o) o.DonHang.Id = x.Id).ToList().Select(Function(c) New ChiTietDonHang() With {.Id = c.Id, .DonGia = c.DonGia, .DonHang = c.DonHang, .SanPham = db.SanPhams.ToList().FirstOrDefault(Function(s) s.Id = c.SanPham.Id), .SoLuong = c.SoLuong}).ToList()}).ToList() _
                                                 .FirstOrDefault(Function(x) x.Id = objB.IdDonHang)
            End Using

            Dim frm = New frmThanhToan
            frm.Ban = objB
            frm.DonHang = dh
            AddHandler frm.OnThanhToan, AddressOf DaThanhToan
            frm.ShowDialog()
        Else
            MessageBox.Show("Chọn bàn trước", "Thông báo")
        End If
    End Sub

    Private Sub DaThanhToan(sender As System.Object, e As System.EventArgs)
        Dim b As Ban = sender

        lvHoaDon.Items.Clear()
        'Set Icon
        SetIconBan(b, 0)
        lblBan.Text = String.Format("{0}: Chưa sử dụng ", b.Ten)
        SetThanhTien(0)
        'Xử lý cac button
        btnMoBan.Enabled = True
        tsbGopBan.Enabled = False
        tsbThanhToan.Enabled = False
        tsbHuyBan.Enabled = False

        btnThanhToan.Enabled = False
        btnGopBan.Enabled = False
        btnBoMon.Enabled = False
        btnThemMon.Enabled = False
        btnThanhToan.Enabled = False

    End Sub

    Private Sub btnThongKe_Click(sender As System.Object, e As System.EventArgs) Handles btnThongKe.Click, tsbTongKe.Click, ThốngKêHóaĐơnToolStripMenuItem.Click
        Dim frm = New frmThongKe
        frm.ShowDialog()
    End Sub

    Private Sub btnGopBan_Click(sender As System.Object, e As System.EventArgs) Handles btnGopBan.Click

        Dim objB As Ban = lblBan.Tag

        If objB IsNot Nothing AndAlso objB.DaSuDung Then
            Dim frm = New frmGopBan
            frm.BanChinh = objB
            AddHandler frm.OnGopXong, AddressOf DaGopXong
            AddHandler frm.OnGopXongDonHang, AddressOf DaGopXongDonHang
            frm.ShowDialog()
        End If
       
    End Sub

    Private Sub DaGopXong(sender As System.Object, e As System.EventArgs)
        Dim b As Ban = sender

        lvHoaDon.Items.Clear()
        'Set Icon
        SetIconBan(b, 0)
    End Sub

    Private Sub DaGopXongDonHang(sender As System.Object, e As System.EventArgs)
        Dim b As DonHang = sender
        SetThanhTien(b.ThanhTien)
        LoadLvHoaDon(b)
    End Sub
    Private Sub DoiMatKhauToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DoiMatKhauToolStripMenuItem.Click
        Dim frm = New frmDoiMatKhau
        frm.ShowDialog()
    End Sub

    Private Sub lvMon_MouseDoubleClick(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles lvMon.MouseDoubleClick
        lvMon_SelectedIndexChanged(sender, e)
        btnThemMon_Click(sender, e)
    End Sub

   
    Private Sub lvBan_MouseDoubleClick(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles lvBan.MouseDoubleClick
        ''lvBan_SelectedIndexChanged(sender, e)
        If sender.SelectedItems.Count = 0 Then Return
        Dim obj As Ban = sender.SelectedItems(0).Tag
        If Not IsNothing(obj) Then
            If obj.DaSuDung Then
                If MessageBox.Show("Bạn có thực sự muốn thanh toán", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Yes Then
                    btnThanhToan_Click(sender, e)
                End If
            Else
                If MessageBox.Show("Bạn có thực sự muốn mở bàn", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Yes Then
                    btnMoBan_Click(sender, e)
                End If
            End If
        End If
    End Sub

   
    Private Sub lvHoaDon_MouseDoubleClick(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles lvHoaDon.MouseDoubleClick
        If sender.SelectedItems.Count = 0 Then Return
        If MessageBox.Show("Bạn có thực sự muốn bỏ món", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Yes Then
            btnBoMon_Click(sender, e)
        End If
    End Sub

    Private Sub ThoátToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ThoátToolStripMenuItem.Click
        Application.Exit()

    End Sub

    Private Sub VềTácGiảToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles VềTácGiảToolStripMenuItem.Click
        Dim frm = New frmAbout
        frm.ShowDialog()
    End Sub

  

    Private Sub frmMain_Resize(sender As System.Object, e As System.EventArgs) Handles MyBase.Resize
        'Set lai chiều rộng của Col Tên trong lvHoaDon
        ColumnHeader5.Width = lvHoaDon.Width - 230

    End Sub
End Class

